package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryByID(Long id) {
        //查询缓存
        Map<Object, Object> ShopMap= stringRedisTemplate.opsForHash().entries("cache:shop:" + id);
        //判断缓存是否存在
        if(! ShopMap.isEmpty()){
            //存在，返回
            Shop Shop = BeanUtil.mapToBean(ShopMap, Shop.class, true);
            return Result.ok(Shop);
        }
        //不存在，查询数据库
        Shop Shop = this.getById(id);
        //判断是否存在于数据库
        if(Shop == null){
            //不存在
            return Result.fail("店铺不存在");
        }
        //存在，写入缓存
        Map<String, Object> ShopMapWrite = BeanUtil.beanToMap(Shop);
        // 将 Map 中的所有值转换为 String 类型
        Map<String, String> stringMap = new HashMap<>();
        for (Map.Entry<String, Object> entry : ShopMapWrite.entrySet()) {
            stringMap.put(entry.getKey(), String.valueOf(entry.getValue()));
        }

        stringRedisTemplate.opsForHash().putAll("cache:shop:" + id, stringMap);
        //设置有效期，实现超时剔除
        stringRedisTemplate.expire("cache:shop:" + id,30, TimeUnit.MINUTES);

        return Result.ok(Shop);
    }


    /**
     * 更新店铺信息
     * @param shop
     */
    @Override
    @Transactional
    public Result UpdateShop(Shop shop) {
        if(shop == null){
            return Result.fail("店铺信息不能为空");
        }
        //操作数据库
        updateById(shop);
        //删除缓存
        stringRedisTemplate.delete("cache:shop:"+shop.getId());
       return Result.ok();
        


    }
}
